package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.dao.CoursesDao;
import model.dao.MajorDao;
import model.dao.SurveyDetailDao;
import model.dao.TeacherDao;
import model.dao.Teacher_CourseDao;
import model.entity.SurveyDetail;

/**
 * Servlet implementation class SetSurDetail
 */
@WebServlet("/SetSurDetail")
public class SetSurDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SetSurDetail() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 定义一个标志，判断是否将匹配的数据加入到数据库
		
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		
		try {
			boolean isDo = false;

			// 获取前端提交的session参数
			HttpSession session = request.getSession();
			String[] teacherNameArray = (String[]) session.getAttribute("teacherNameArray");
			String[] courseArray = (String[]) session.getAttribute("courseArray");
			String major = (String) session.getAttribute("major");
			String useName = (String) session.getAttribute("userName");

			// 实例化专业，老师，课程，老师课程，调查细节对象
			MajorDao md = new MajorDao();
			TeacherDao tcd = new TeacherDao();
			CoursesDao cd = new CoursesDao();
			Teacher_CourseDao tccd = new Teacher_CourseDao();
			SurveyDetailDao sdd = new SurveyDetailDao();

			// 定义查询时需要用到的数据库字段名称
			String id = new String("id");
			String name = new String("name");
			String teacher_id = new String("teacher_id");
			String course_id = new String("course_id");

			// 获取专业id
			Integer majorid = 0;
			List<Object> majorIdList = md.getSigleSelect(id, name, major);
			for (Object obj : majorIdList) {
				majorid = (Integer) obj;
			}
			
			// 获取前端评分完后提交的分数
			Enumeration<String> paramName = request.getParameterNames();
			while (paramName.hasMoreElements()) {
				// 获取提交时服务器的时间作为数据库中的date值
				Date curTime = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String time = sdf.format(curTime);

				// 获取被点击的分数radio
				String paraName = (String) paramName.nextElement();

				// 截取被点击的radio的name，并截取除了前4位的值作为调查项的id
				String paraN = paraName.substring(4, paraName.length());
				int contentid = Integer.valueOf(paraN);

				// 获取被点击的radio的value值作为分数
				int score = Integer.valueOf(request.getParameter(paraName));

				// 取出前端提交的教师名字
				for (String teacher : teacherNameArray) {
					// 查询教师的id
					List<Object> teaIdList = tcd.getSigleSelect(id, name, teacher);
					// 取出查询的教师的id
					for (Object obj1 : teaIdList) {
						Integer teacherid = (Integer) obj1;
						// 取出前端提交过来的课程名字
						for (String course : courseArray) {
							// 查询课程的id
							List<Object> courseIdList = cd.getSigleSelect(id, name, course);
							// 取出查询课程的id
							for (Object courseid : courseIdList) {
								// 查询当前教师所对应的所有课程id
								List<Object> matchCourseId = tccd.getSigleSelect(course_id, teacher_id, obj1);
								// 检查前courseid是否是属于该教师（obj1）
								for (Object matchid : matchCourseId) {
									// 如果当前课程courseid属于该教师（obj1），则将标志isDo的值变为true
									if ((Integer) courseid == (Integer) matchid) {
										isDo = true;
									}
								}

								// 如果当前课程courseid属于该教师（obj1），则将评分结果插入到数据库
								if (isDo) {
									SurveyDetail sd = new SurveyDetail();
									sd.setDate(time);
									sd.setPeriod(13);
									sd.setScore(score);
									sd.setContent_ID(contentid);
									sd.setTeacher_ID(teacherid);
									sd.setIdentifier(useName);
									sd.setMajor_id(majorid);
									sd.setCourse_id((Integer) courseid);
									sdd.insertData(sd);
									isDo = false;
								}
							}
						}
					}
				}
			}
			
			//当提交成功时向前端输出成功提示信息：successful。
			out.print("successful");
		} catch (Exception e) {
            //如果抛出异常则输出unsuccessful.
			out.print("unsuccessful");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
